package com.diaohw.module.websocket.service.ws.handle;

import cn.hutool.core.util.StrUtil;
import com.diaohw.module.websocket.obj.vo.MsgVO;
import com.diaohw.module.websocket.properties.HttpMsgProcessProperties;
import com.diaohw.platform.framework.web.ContentType;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import static com.diaohw.module.websocket.properties.WsMessageProperties.HTTP_CONFIG;


@Service
@ConditionalOnProperty(HTTP_CONFIG)
public class HttpHandle {


    @Resource
    private RestTemplate restTemplate;

    @SneakyThrows
    public void execute(HttpMsgProcessProperties config, MsgVO message) {


        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(getMediaType(config.getContentType()));
        if (StrUtil.isNotBlank(config.getAuthorization()) && StrUtil.isNotBlank(message.getToken())) {
            headers.add(config.getAuthorization(), message.getToken());
        }
        HttpEntity<MsgVO> entity = new HttpEntity<>(message, headers);


        ResponseEntity<String> exchange = restTemplate.exchange(config.getUrl(), config.getMethod(), entity, String.class);

//        HttpUtil.post(config.getUrl(), JsonUtil.toJsonString(message));

    }


    private MediaType getMediaType(ContentType contentType) {
        return switch (contentType) {
            case JSON -> MediaType.APPLICATION_JSON;
            case TEXT -> MediaType.TEXT_PLAIN;
            case XML -> MediaType.APPLICATION_XML;
            default -> MediaType.APPLICATION_FORM_URLENCODED;
        };
    }


}
